<?php

class OrdersController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/admin/main';

	public function init(){
        Yii::app()->user->loginUrl = array('/admin/site/login');
        parent::init();
    }

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('login','logout'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update', 'index', 'view', 'new', 'edit', 'approve', 'decline'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

  public function actionApprove($id)
  {
    $order=DetailOrders::model()->find('id = :id', array(':id'=>$_GET['id']));
    $order->status = 1;
    $order->order->modified_at = date('Y-m-d H:i:s');

    if(isset($_POST['notes']))
    {
      $order->approval_notes = $_POST['notes'];
    }

    if ($order->save())
    {
      $order->order->save();
      Yii::app()->user->setFlash('success', 'Success');
      Yii::app()->user->setFlash('content', 'You have approved an order.');
      $this->redirect(bu('admin/orders/'.$order->order->id));
    }

    Yii::app()->user->setFlash('error', 'Error');
    Yii::app()->user->setFlash('content', 'Cannot approved order. Please try again.');
  }

  public function actionDecline($id)
  {
    $order=DetailOrders::model()->find('id = :id', array(':id'=>$_GET['id']));
    $order->status = 0;
    $order->order->modified_at = date('Y-m-d H:i:s');
    $order->approval_notes = '';
    if ($order->save())
    {
      $order->order->save();
      Yii::app()->user->setFlash('success', 'Success');
      Yii::app()->user->setFlash('content', 'You have decline an order.');
      $this->redirect(bu('admin/orders/'.$order->order->id));
    }

    Yii::app()->user->setFlash('error', 'Error');
    Yii::app()->user->setFlash('content', 'Cannot decline order. Please try again.');
  }

	public function actionView($id)
	{
    $order = Orders::model()->find('id = :id', array(':id' => $id));
		$this->render('view',array(
			'order'=>$order,
		));
	}

	public function actionDelete()
	{
		$detail = DetailOrders::model()->find('id = :id', array(':id'=>$_GET['id']));
    $order_id = $detail->order_id;
		$detail->delete();
    
    $other_details = DetailOrders::model()->findAll('order_id = :order_id', array(':order_id' => $order_id));
    if(!$other_details){
      $order = Orders::model()->find('id = :id', array(':id' => $order_id));
      $order->delete();
    }
    
		$this->redirect(bu('admin/orders/'));
	}

	public function actionIndex()
	{
    $orders = Orders::model()->findAll();
		//$detail=DetailOrders::model()->with('order')->findAll();

		$this->render('index',array(
			'orders' => $orders,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Orders::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='orders-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
